package com.xiaoyu.izf.service;


import com.xiaoyu.izf.model.page.DataTableBean;
import com.xiaoyu.izf.model.page.ParamListBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.StringUtils;


public class BaseService {
	static Logger log = LoggerFactory.getLogger(BaseService.class);
	
	public PageRequest buildPageRequest(int pageNumber, int pagzSize, String sortType) {
        Sort sort = new Sort(Direction.DESC, sortType);;
        return new PageRequest(pageNumber - 1, pagzSize, sort);
    }
	
	public PageRequest buildPageRequestSort(int pageNumber, int pagzSize, String defaultFieldName, String fieldName, String compositorType) {
        Sort sort = null;
        if(StringUtils.isEmpty(fieldName)){
        	if(StringUtils.isEmpty(compositorType)||"desc".equals(compositorType)){
        		sort = new Sort(Direction.DESC, defaultFieldName);
        	}else {
        		sort = new Sort(Direction.ASC, defaultFieldName);
			}
        }else{
        	if(StringUtils.isEmpty(compositorType)||"desc".equals(compositorType)){
        		sort = new Sort(Direction.DESC, fieldName);
        	}else {
        		sort = new Sort(Direction.ASC, fieldName);
			}
        }
        return new PageRequest(pageNumber - 1, pagzSize, sort);
    }

	public <T> DataTableBean dataTableBean(Page<T> page, ParamListBean param){
		DataTableBean data = new DataTableBean();
		data.setsEcho(param.getsEcho());
		data.setiTotalDisplayRecords((int)page.getTotalElements());
		data.setiTotalRecords((int)page.getTotalElements());
		data.setAaData(page.getContent());
		return data;
	}
}
